package com.threepure.penpipe.util;

import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;

/**
 * @author ThreePure
 * @date 2021/11/20 11:45
 * @description: 实现单击、双击的工具类
 * @since 1.8
 */
public class MyClickListener implements View.OnTouchListener {

    /**控件id*/
    private int id;

    /**双击间四百毫秒延时*/
    private static int timeout=400;

    /**记录连续点击次数*/
    private int clickCount = 0;

    private Handler handler;

    private MyClickCallBack myClickCallBack;


    public MyClickListener(int id, MyClickCallBack myClickCallBack) {
        this.id = id;
        this.myClickCallBack = myClickCallBack;
        handler = new Handler();
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            clickCount++;
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (clickCount == 1) {
                        myClickCallBack.oneClick(id);
                    }else if(clickCount==2){
                        myClickCallBack.doubleClick(id);
                    }
                    //删除所有挂起的回调帖子和obj为令牌的已发送邮件。如果令牌为null，则将删除所有回调和消息。
                    handler.removeCallbacksAndMessages(null);
                    //清空handler延时，并防内存泄漏
                    clickCount = 0;//计数清零
                }
                //延时timeout后执行run方法中的代码
            },timeout);
        }
        //让点击事件继续传播，方便再给View添加其他事件监听
        return false;
    }

    public interface MyClickCallBack{
        /**点击一次的回调*/
        void oneClick(int id);
        /**连续点击两次的回调*/
        void doubleClick(int id);
    }
}